package com.leetone;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* @ClassName: ReadWriteLockTest
* @Description: 【读写锁单独使用,读的时候可以并发，写的时候是带顺序阻塞的】
* @date 2018年8月29日 下午2:41:39
* @Company: 上海未泰信息技术有限公司
* @author:[谭磊][leetone123@163.com]
*/
public class ReadWriteLockTest {
	public static void main(String[] args) {
		final Countz count = new Countz();
		for(int i=0;i<2;i++)
		{
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					count.get();
				}
			}.start();
		}
		for(int i=0;i<2;i++)
		{
			new Thread() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					super.run();
					count.put();
				}
			}.start();
		}
	}
}
class Countz{
	private final ReentrantReadWriteLock rw1 = new ReentrantReadWriteLock();
	public void get() {
		try {
			//上读锁，其他线程只能读不能写，具有高并发性
			rw1.readLock().lock();
			System.out.println(Thread.currentThread().getName()+"\t read start");
			Thread.sleep(1000L);
			System.out.println(Thread.currentThread().getName()+"\t read end");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//最好在finally里面释放读锁
			rw1.readLock().unlock();
		}
	}
	
	public void put() {
		try {
			//上写锁，具有阻塞性,其他线程不能读不能写
			rw1.writeLock().lock();
			System.out.println(Thread.currentThread().getName()+"\t write start");
			Thread.sleep(1000L);
			System.out.println(Thread.currentThread().getName()+"\t write end");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			rw1.writeLock().unlock();
		}
	}
}
